package edu.jmu.controller;

import edu.jmu.domain.Admin;
import edu.jmu.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService as;

    @RequestMapping("login")
    public String login(Admin admin, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Admin loginAdmin = as.login(admin);
        HttpSession session = request.getSession();
        session.setAttribute("admin",loginAdmin);
        if(loginAdmin!=null){
            return "admin";
        }
        request.setAttribute("msg","密码或账号错误！");
        request.getRequestDispatcher("/admin_login.jsp").forward(request,response);
        return null;
    }

    @RequestMapping("index")
    public String index(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Admin admin = (Admin)session.getAttribute("admin");
        if(admin!=null){
            return "admin";
        }
        request.getRequestDispatcher("/admin_login.jsp").forward(request,response);
        return null;
    }
    @RequestMapping("showNewsInfo")
    public String showNewsInfoAdmin(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Admin admin = (Admin)session.getAttribute("admin");
        if(admin!=null){
            return "news_info";
        }
        request.getRequestDispatcher("/admin_login.jsp").forward(request,response);
        return null;
    }

    @RequestMapping("showDraftsInfo")
    public String showDraftsInfo(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Admin admin = (Admin)session.getAttribute("admin");
        if(admin!=null){
            return "news_drafts";
        }
        request.getRequestDispatcher("/admin_login.jsp").forward(request,response);
        return null;
    }


    @RequestMapping("shutdown")
    public void shutdown(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.setAttribute("admin",null);
        request.getRequestDispatcher("/index.jsp").forward(request,response);
    }






}
